package com.easychat.spring;

import com.easychat.entity.constants.Constants;
import com.easychat.redis.RedisComponent;
import com.easychat.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Component
public class HeartbeatCheckerTask {
    @Resource
    private RedisComponent redisComponent;

    @Resource
    private RedisUtils redisUtils;


    @Scheduled(fixedRate = 60000)
    public void checkUserHeartBeat() {
        Set<String> keys = redisComponent.getAllOnlineUsers();
        if (keys == null || keys.isEmpty()) return;

        long now = System.currentTimeMillis();

        for (String key : keys) {
            String userId = key.replace(Constants.REDIS_KEY_WS_USER_HEART_BEAT, "");
            Long last = (Long) redisUtils.get(key);
            if (last == null) continue;

            if (now - last > 90 * 1000L) {
                log.info("用户 {} 超过 90 秒未发送心跳，判定为离线", userId);
                redisComponent.markUserOffline(userId);
            }
        }
    }

}

